package com.web.controller.store;

import com.domain.store.Catalog;
import com.domain.store.Company;
import com.domain.store.Course;
import com.domain.store.Question;
import com.github.pagehelper.PageInfo;
import com.service.store.*;
import com.utils.BeanUtil;
import com.web.controller.BaseServlet;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.List;

@WebServlet("/store/question")
public class QuestionServlet extends HttpServlet {
    ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
    QuestionService qs= (QuestionService) ac.getBean("questionService");
    CompanyService cps= (CompanyService)ac.getBean("companyService");
    CatalogService cs= (CatalogService)ac.getBean("catalogService");
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        String operation = request.getParameter("operation");
        if ("list".equals(operation)){
            //调用查询方法
            list(request,response);
        }else if ("toAdd".equals(operation)){
            toAdd(request,response);
        }else if ("save".equals(operation)){
            //添加方法
            try {
                save(request,response);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }else if ("delete".equals(operation)){
            //删除方法
            delete(request,response);
        }else if ("toEdit".equals(operation)){
            toEdit(request,response);
        }else if ("edit".equals(operation)){
            //修改
            try {
                edit(request,response);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }else if ("toUpload".equals(operation)){
            //跳转至上传图片页面
            toUpload(request,response);
        }else if ("testUpload".equals(operation)){
            //上传图片
            try {
                testUpload(request,response);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }else if ("toExport".equals(operation)){
            toExport(request,response);
        }
    }

    private void toExport(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //将返回数据类型设置为xlsx类型
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        String fileName = new String("题目文件.xlsx".getBytes(),"iso8859-1");
        response.addHeader("Content-Disposition","attachment;fileName="+fileName);
        //调用业务层代码,获取报表
        ByteArrayOutputStream bos = qs.toExport();
        ServletOutputStream os = response.getOutputStream();
        //将文件提取处理写入至浏览器
        bos.writeTo(os);
        //刷新流
        os.flush();
        bos.close();
    }

    private void testUpload(HttpServletRequest request, HttpServletResponse response) throws Exception {
        //判断是否支持文件上传操作
        if (ServletFileUpload.isMultipartContent(request)){
            //创建磁盘对象
            DiskFileItemFactory factory = new DiskFileItemFactory();
            //文件上传核心对象
            ServletFileUpload fileUpload = new ServletFileUpload(factory);
            //读取数据
            List<FileItem> fileItems = fileUpload.parseRequest(request);
            //循环数据
            for (FileItem fileItem : fileItems) {
                //判断当前表单是否为文件表单
                if (!fileItem.isFormField()){
                    //将文件写入至upload下
                    fileItem.write(new File(this.getServletContext().getRealPath("upload"),fileItem.getName()));
                }
            }
        }
    }

    private void toUpload(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //转发
        request.getRequestDispatcher("/WEB-INF/pages/store/question/testFileUpload.jsp").forward(request,response);
    }

    private void edit(HttpServletRequest request, HttpServletResponse response) throws Exception {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        //判断是否支持文件上传操作
        if (ServletFileUpload.isMultipartContent(request)){
            //创建磁盘对象
            DiskFileItemFactory factory = new DiskFileItemFactory();
            //文件上传核心对象
            ServletFileUpload fileUpload = new ServletFileUpload(factory);
            //读取数据
            List<FileItem> fileItems = fileUpload.parseRequest(request);
            //封装数据
            Question question = BeanUtil.fillBean(fileItems, Question.class);

            boolean flag = false;
            for (FileItem fileItem : fileItems) {
                //判断当前表单是否为文件表单
                if (StringUtils.isNoneBlank(fileItem.getName())){
                    flag = true;
                    break;
                }
            }
            //调用业务层代码
            qs.update(question,flag);
            //循环数据
            for (FileItem fileItem : fileItems) {
                //判断当前表单是否为文件表单
                if (!fileItem.isFormField()){
                    //将文件写入至upload下
                    fileItem.write(new File(this.getServletContext().getRealPath("upload"),question.getId()));
                }
            }
        }
        //重定向
        response.sendRedirect(request.getContextPath()+"/store/question?operation=list");
    }

    private void toEdit(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        //获得数据id
        String id = request.getParameter("id");
        //调用业务层代码
        Question question = qs.findById(id);
        //将数据存入域中
        request.setAttribute("question",question);
        List<Company> all = cps.findAll();
        request.setAttribute("companyList",all);
        List<Catalog> list = cs.findAll();
        request.setAttribute("catalogList",list);
        //转发
        request.getRequestDispatcher("/WEB-INF/pages/store/question/update.jsp").forward(request,response);
    }

    private void delete(HttpServletRequest request, HttpServletResponse response) throws IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        //得到参数id
        Question question = BeanUtil.fillBean(request, Question.class);
        //调用业务层
        qs.delete(question);
        //重定向
        response.sendRedirect(request.getContextPath()+"/store/question?operation=list");
    }

    private void save(HttpServletRequest request, HttpServletResponse response) throws Exception {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        //判断是否支持文件上传操作
        if (ServletFileUpload.isMultipartContent(request)){
            //创建磁盘对象
            DiskFileItemFactory factory = new DiskFileItemFactory();
            //文件上传核心对象
            ServletFileUpload fileUpload = new ServletFileUpload(factory);
            //读取数据
            List<FileItem> fileItems = fileUpload.parseRequest(request);
            //封装数据
            Question question = BeanUtil.fillBean(fileItems, Question.class);

            //设置旗帜变量
            boolean flag = false;
            for (FileItem fileItem : fileItems) {
                //判断当前表单是否为文件表单
                if (StringUtils.isNoneBlank(fileItem.getName())){
                    flag = true;
                    break;
                }
            }
            //调用业务层代码
            String id = qs.save(question,flag);
            //循环数据
            for (FileItem fileItem : fileItems) {
                //判断当前表单是否为文件表单
                if (!fileItem.isFormField()){
                    //将文件写入至upload下
                    fileItem.write(new File(this.getServletContext().getRealPath("upload"),id));
                }
            }
        }
        response.sendRedirect(request.getContextPath()+"/store/question?operation=list");
    }

    private void toAdd(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //关联企业和题目所属类别
        List<Company> all = cps.findAll();
        request.setAttribute("companyList",all);
        List<Catalog> list = cs.findAll();
        request.setAttribute("catalogList",list);
        //转发至添加页面
        request.getRequestDispatcher("/WEB-INF/pages/store/question/add.jsp").forward(request,response);
    }

    private void list(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        //定义分页`参数
        int page = 1;
        int size = 5;
        //得到分页参数
        //判断所得参数是否为空,如果为空,使用默认得1,5
        if (StringUtils.isNoneBlank(request.getParameter("page"))){
            page = Integer.parseInt(request.getParameter("page"));
        }
        if (StringUtils.isNoneBlank(request.getParameter("size"))){
            size = Integer.parseInt(request.getParameter("size"));
        }
        //调用业务层方法
        PageInfo all = qs.findAll(page, size);
        //将数据存至域中
        request.setAttribute("page",all);
        //转发
        request.getRequestDispatcher("/WEB-INF/pages/store/question/list.jsp").forward(request,response);

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}
